from django.contrib import admin
from .models import *
from django.utils.text import capfirst # 分类排序

@admin.register(Product)
class Product_admin(admin.ModelAdmin):
    all_fields = list(key.name for key in Product._meta.fields)
    list_display = all_fields
    search_fields = ['name']
    list_per_page = 25  # 每页显示条数
    ordering = ['-gmt_modified']

@admin.register(EnvConfig)
class EnvConfig_admin(admin.ModelAdmin):
    all_fields = list(key.name for key in EnvConfig._meta.fields)
    list_display = all_fields
    search_fields = ['name']
    list_per_page = 25  # 每页显示条数
    ordering = ['-gmt_modified']

@admin.register(Application)
class Application_Account_admin(admin.ModelAdmin):
    all_fields = list(key.name for key in Application._meta.fields)
    list_display = all_fields

    search_fields = ['name']
    list_per_page = 25  # 每页显示条数
    ordering = ['-gmt_modified']



# 排序
def find_model_index(name):
    count = 0
    for model, model_admin in admin.site._registry.items():
        if capfirst(model._meta.verbose_name_plural) == name:
            return count
        else:
            count += 1
    return count


def index_decorator(func):
    def inner(*args, **kwargs):
        templateresponse = func(*args, **kwargs)
        for app in templateresponse.context_data['app_list']:
            app['models'].sort(key=lambda x: find_model_index(x['name']))
        return templateresponse
    return inner
admin.site.index = index_decorator(admin.site.index)
admin.site.app_index = index_decorator(admin.site.app_index)